package com.wx.lock.zooKeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.Objects;

/**
 * @author wx
 * @Description: 锁监听
 * @date 2018/11/29 002919:38
 */
public class LockWatcher implements Watcher {
    private DistributedLock distributedLock;
    private String THREAND_NAME = Thread.currentThread().getName();

    public LockWatcher(DistributedLock distributedLock) {
        this.distributedLock = distributedLock;
    }
    
    /**
     * @description: 监听节点
     * @author: wx
     * @date: 2018/11/30 0030
     * @param event
     * @return: void
     */
    @Override
    public void process(WatchedEvent event) {
        if (Objects.equals(event.getType(), Event.EventType.NodeDeleted) && Objects.equals(event.getPath(), distributedLock.getWaiPath())) {
            System.out.println(THREAND_NAME + ":" + distributedLock.getWaiPath() + "节点已经被删除");
            if (distributedLock.checkMinPath()) {
                distributedLock.run();
                distributedLock.unLock();
            }
        }
    }

}
